;(function () {
  const vscode = acquireVsCodeApi();
  const obj = vscode.getState() || {};
  const state = new Proxy(obj, {
    set(target, key, value) {
      vscode.setState({ ...obj, [key]: value });
      target[key] = value;
      return true;
    },
  });

  const textual = document.querySelector('#textual');
  const btn = document.querySelector('.btn_t5294jx8');
  const panle = document.querySelector('.panle');

  textual.value = state.textualText || '';
  panle.innerHTML = state.panleText || '';

  textual.addEventListener('input', e => {
    state.textualText = e.target.value;
  });

  btn.addEventListener('click', () => {
    if (state.textualText === '') {
      return;
    }
    vscode.postMessage({
      type: 'fetch',
      data: state.textualText,
    });
  });
  // 给翻译面板设置结果
  const setPanleValue = value => {
    let str = '';
    if (Array.isArray(value)) {
      str = value.map(i => i.dst).join('\n');
    }
    panle.innerText = str || '无';
  };

  const clearState = () => {
    textual.value = '';
    panle.innerHTML = '';
    Object.keys(obj).forEach(k=>{
      delete state[k];
    });
    vscode.setState({});
  };

  window.addEventListener('message', ({ data }) => {
    switch (data.type) {
      case 'dsc':
        setPanleValue(data.data);
        break;
      case 'clear':
        clearState();
        break;
      default:
        break;
    }
  });
})();
